package com.library.controller;

import com.library.dao.BookReviewDao;
import com.library.entity.BookReview;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/bookReview")
public class BookReviewController {
    @Autowired
    private BookReviewDao bookReviewDao;

    @PostMapping("/add")
    public ModelAndView addReview(HttpServletRequest request) {
        HttpSession session = request.getSession();
        Long readerId = null;
        Object readerIdObj = session.getAttribute("readerId");
        if (readerIdObj instanceof Number) {
            readerId = ((Number) readerIdObj).longValue();
        }
        if (readerId == null) {
            return new ModelAndView("redirect:/login.html");
        }
        Long bookId = Long.parseLong(request.getParameter("bookId"));
        Long rating = Long.parseLong(request.getParameter("rating"));
        String reviewText = request.getParameter("reviewText");

        if (bookReviewDao.hasUserReviewed(bookId, readerId)) {
            return new ModelAndView("redirect:/book_detail.html?bookId=" + bookId + "&msg=您已经评价过这本书了");
        }

        BookReview review = new BookReview();
        review.setBookId(bookId);
        review.setReaderId(readerId);
        review.setRating(rating.intValue());
        review.setReviewText(reviewText);

        if (bookReviewDao.addReview(review) > 0) {
            return new ModelAndView("redirect:/book_detail.html?bookId=" + bookId + "&msg=评论成功！");
        } else {
            return new ModelAndView("redirect:/book_detail.html?bookId=" + bookId + "&msg=评价失败，请稍后重试");
        }
    }

    @GetMapping("/list")
    public ModelAndView listReviews(@RequestParam("bookId") Long bookId) {
        List<BookReview> reviews = bookReviewDao.getBookReviews(bookId);
        double averageRating = bookReviewDao.getAverageRating(bookId);
        ModelAndView modelAndView = new ModelAndView("book_detail");
        modelAndView.addObject("reviews", reviews);
        modelAndView.addObject("averageRating", averageRating);
        return modelAndView;
    }

    @PostMapping("/delete")
    @ResponseBody
    public Map<String, Object> deleteReview(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 获取并打印参数，用于调试
            String reviewIdStr = request.getParameter("reviewId");
            String bookIdStr = request.getParameter("bookId");

            System.out.println("Received reviewId: " + reviewIdStr);
            System.out.println("Received bookId: " + bookIdStr);

            if (reviewIdStr == null || bookIdStr == null) {
                result.put("success", false);
                result.put("msg", "缺少必要参数");
                return result;
            }

            Long reviewId = Long.parseLong(reviewIdStr);
            Long bookId = Long.parseLong(bookIdStr);

            if (bookReviewDao.deleteReview(reviewId) > 0) {
                result.put("success", true);
                result.put("msg", "删除成功！");
            } else {
                result.put("success", false);
                result.put("msg", "删除评价失败，请稍后重试");
            }
        } catch (NumberFormatException e) {
            result.put("success", false);
            result.put("msg", "参数格式错误: " + e.getMessage());
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", "系统错误: " + e.getMessage());
        }
        return result;
    }

    // 这个方法可以保留或删除，取决于你的应用需求
    @GetMapping("")
    public ModelAndView bookReviewPage(@RequestParam String msg, @RequestParam String redirectUrl) {
        ModelAndView mv = new ModelAndView("bookReview");
        mv.addObject("msg", msg);
        mv.addObject("redirectUrl", redirectUrl);
        return mv;
    }
}